package com.zecan.blog.service.impl;

import com.zecan.blog.common.status.TagStatus;
import com.zecan.blog.controller.exception.TagException;
import com.zecan.blog.dao.TagMapper;
import com.zecan.blog.entity.Article;
import com.zecan.blog.entity.Tag;
import com.zecan.blog.service.TagService;
import com.zecan.blog.vo.article.ArticleMsgVo;
import com.zecan.blog.vo.tag.TagMsgVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName TagServiceImpl
 * @Description
 * @date 2022/11/3 21:35
 * @Version 1.0
 */
@Service
public class TagServiceImpl implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public List<Tag> getTagListAll() {
        return tagMapper.findTagByLimit();
    }

    @Override
    public TagMsgVo selectArticleByTagId(String tagIds, Integer offset, Integer limit) {

        List<Article> articleByTagId = tagMapper.findArticleByTagId(tagIds, offset, limit);
        if (articleByTagId.size() == 0) {
            throw new TagException(TagStatus.TAG_FIND_TO_ARTICLE_FAILURE);
        }

        List<ArticleMsgVo> articleMsgVos = new ArrayList<>();
        for (Article article : articleByTagId) {
            articleMsgVos.add(ArticleMsgVo.buildArticleMsgVo(article,false,false,false));
        }
        // 获取总数
        Integer tagIdCount = tagMapper.findArticleByTagIdCount(tagIds);

        return TagMsgVo.tagMsgBuilder(articleMsgVos, tagIdCount);
    }

    @Override
    public void updateTagName(Integer tagId,String newTagName) {
        // 修改
        // Todo: 事务
      tagMapper.updateTagNameById(tagId, newTagName);
    }

    @Override
    public void deleteTag(Integer tagId) {
        tagMapper.deleteTagById(tagId);
    }

    @Override
    public void insertTag(String newTagName) {
        tagMapper.insertTag(newTagName);
    }

    @Override
    public Integer getTagListCount() {
        return tagMapper.selectTagCount();
    }
}
